<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>9.3. collections — High-performance container datatypes &mdash; Python v2.6.2 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2.6.2',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python v2.6.2 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python v2.6.2 documentation" href="../index.html" />
    <link rel="up" title="9. Data Types" href="datatypes.html" />
    <link rel="next" title="9.4. heapq — Heap queue algorithm" href="heapq.html" />
    <link rel="prev" title="9.2. calendar — General calendar-related functions" href="calendar.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
 

  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../modindex.html" title="Global Module Index"
             accesskey="M">modules</a> |</li>
        <li class="right" >
          <a href="heapq.html" title="9.4. heapq — Heap queue algorithm"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="calendar.html" title="9.2. calendar — General calendar-related functions"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v2.6.2 documentation</a> &raquo;</li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
          <li><a href="datatypes.html" accesskey="U">9. Data Types</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="module-collections">
<h1>9.3. <tt class="xref docutils literal"><span class="pre">collections</span></tt> &#8212; High-performance container datatypes<a class="headerlink" href="#module-collections" title="Permalink to this headline">¶</a></h1>
<p>
<span class="versionmodified">New in version 2.4.</span></p>
<p>This module implements high-performance container datatypes.  Currently,
there are two datatypes, <a title="collections.deque" class="reference internal" href="#collections.deque"><tt class="xref docutils literal"><span class="pre">deque</span></tt></a> and <a title="collections.defaultdict" class="reference internal" href="#collections.defaultdict"><tt class="xref docutils literal"><span class="pre">defaultdict</span></tt></a>, and
one datatype factory function, <a title="collections.namedtuple" class="reference internal" href="#collections.namedtuple"><tt class="xref docutils literal"><span class="pre">namedtuple()</span></tt></a>.</p>
<p>
<span class="versionmodified">Changed in version 2.5: </span>Added <a title="collections.defaultdict" class="reference internal" href="#collections.defaultdict"><tt class="xref docutils literal"><span class="pre">defaultdict</span></tt></a>.</p>
<p>
<span class="versionmodified">Changed in version 2.6: </span>Added <a title="collections.namedtuple" class="reference internal" href="#collections.namedtuple"><tt class="xref docutils literal"><span class="pre">namedtuple()</span></tt></a>.</p>
<p>The specialized containers provided in this module provide alternatives
to Python&#8217;s general purpose built-in containers, <a title="dict" class="reference external" href="stdtypes.html#dict"><tt class="xref docutils literal"><span class="pre">dict</span></tt></a>,
<a title="list" class="reference external" href="functions.html#list"><tt class="xref docutils literal"><span class="pre">list</span></tt></a>, <a title="set" class="reference external" href="stdtypes.html#set"><tt class="xref docutils literal"><span class="pre">set</span></tt></a>, and <a title="tuple" class="reference external" href="functions.html#tuple"><tt class="xref docutils literal"><span class="pre">tuple</span></tt></a>.</p>
<p>Besides the containers provided here, the optional <a title="Interface to Berkeley DB database library" class="reference external" href="bsddb.html#module-bsddb"><tt class="xref docutils literal"><span class="pre">bsddb</span></tt></a>
module offers the ability to create in-memory or file based ordered
dictionaries with string keys using the <a title="bsddb.btopen" class="reference external" href="bsddb.html#bsddb.btopen"><tt class="xref docutils literal"><span class="pre">bsddb.btopen()</span></tt></a> method.</p>
<p>In addition to containers, the collections module provides some ABCs
(abstract base classes) that can be used to test whether a class
provides a particular interface, for example, is it hashable or
a mapping.</p>
<p>
<span class="versionmodified">Changed in version 2.6: </span>Added abstract base classes.</p>
<div class="section" id="abcs-abstract-base-classes">
<h2>9.3.1. ABCs - abstract base classes<a class="headerlink" href="#abcs-abstract-base-classes" title="Permalink to this headline">¶</a></h2>
<p>The collections module offers the following ABCs:</p>
<table border="1" class="docutils">
<colgroup>
<col width="21%" />
<col width="18%" />
<col width="18%" />
<col width="43%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">ABC</th>
<th class="head">Inherits</th>
<th class="head">Abstract Methods</th>
<th class="head">Mixin Methods</th>
</tr>
</thead>
<tbody valign="top">
<tr><td><tt class="xref docutils literal"><span class="pre">Container</span></tt></td>
<td>&nbsp;</td>
<td><tt class="docutils literal"><span class="pre">__contains__</span></tt></td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="xref docutils literal"><span class="pre">Hashable</span></tt></td>
<td>&nbsp;</td>
<td><tt class="docutils literal"><span class="pre">__hash__</span></tt></td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="xref docutils literal"><span class="pre">Iterable</span></tt></td>
<td>&nbsp;</td>
<td><tt class="docutils literal"><span class="pre">__iter__</span></tt></td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="xref docutils literal"><span class="pre">Iterator</span></tt></td>
<td><tt class="xref docutils literal"><span class="pre">Iterable</span></tt></td>
<td><tt class="docutils literal"><span class="pre">__next__</span></tt></td>
<td><tt class="docutils literal"><span class="pre">__iter__</span></tt></td>
</tr>
<tr><td><tt class="xref docutils literal"><span class="pre">Sized</span></tt></td>
<td>&nbsp;</td>
<td><tt class="docutils literal"><span class="pre">__len__</span></tt></td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="xref docutils literal"><span class="pre">Callable</span></tt></td>
<td>&nbsp;</td>
<td><tt class="docutils literal"><span class="pre">__call__</span></tt></td>
<td>&nbsp;</td>
</tr>
<tr><td><tt class="xref docutils literal"><span class="pre">Sequence</span></tt></td>
<td><tt class="xref docutils literal"><span class="pre">Sized</span></tt>,
<tt class="xref docutils literal"><span class="pre">Iterable</span></tt>,
<tt class="xref docutils literal"><span class="pre">Container</span></tt></td>
<td><tt class="docutils literal"><span class="pre">__getitem__</span></tt></td>
<td><tt class="docutils literal"><span class="pre">__contains__</span></tt>. <tt class="docutils literal"><span class="pre">__iter__</span></tt>, <tt class="docutils literal"><span class="pre">__reversed__</span></tt>.
<tt class="docutils literal"><span class="pre">index</span></tt>, and <tt class="docutils literal"><span class="pre">count</span></tt></td>
</tr>
<tr><td><tt class="xref docutils literal"><span class="pre">MutableSequence</span></tt></td>
<td><tt class="xref docutils literal"><span class="pre">Sequence</span></tt></td>
<td><tt class="docutils literal"><span class="pre">__setitem__</span></tt>
<tt class="docutils literal"><span class="pre">__delitem__</span></tt>,
and <tt class="docutils literal"><span class="pre">insert</span></tt></td>
<td>Inherited Sequence methods and
<tt class="docutils literal"><span class="pre">append</span></tt>, <tt class="docutils literal"><span class="pre">reverse</span></tt>, <tt class="docutils literal"><span class="pre">extend</span></tt>, <tt class="docutils literal"><span class="pre">pop</span></tt>,
<tt class="docutils literal"><span class="pre">remove</span></tt>, and <tt class="docutils literal"><span class="pre">__iadd__</span></tt></td>
</tr>
<tr><td><tt class="xref docutils literal"><span class="pre">Set</span></tt></td>
<td><tt class="xref docutils literal"><span class="pre">Sized</span></tt>,
<tt class="xref docutils literal"><span class="pre">Iterable</span></tt>,
<tt class="xref docutils literal"><span class="pre">Container</span></tt></td>
<td>&nbsp;</td>
<td><tt class="docutils literal"><span class="pre">__le__</span></tt>, <tt class="docutils literal"><span class="pre">__lt__</span></tt>, <tt class="docutils literal"><span class="pre">__eq__</span></tt>, <tt class="docutils literal"><span class="pre">__ne__</span></tt>,
<tt class="docutils literal"><span class="pre">__gt__</span></tt>, <tt class="docutils literal"><span class="pre">__ge__</span></tt>, <tt class="docutils literal"><span class="pre">__and__</span></tt>, <tt class="docutils literal"><span class="pre">__or__</span></tt>
<tt class="docutils literal"><span class="pre">__sub__</span></tt>, <tt class="docutils literal"><span class="pre">__xor__</span></tt>, and <tt class="docutils literal"><span class="pre">isdisjoint</span></tt></td>
</tr>
<tr><td><tt class="xref docutils literal"><span class="pre">MutableSet</span></tt></td>
<td><tt class="xref docutils literal"><span class="pre">Set</span></tt></td>
<td><tt class="docutils literal"><span class="pre">add</span></tt> and
<tt class="docutils literal"><span class="pre">discard</span></tt></td>
<td>Inherited Set methods and
<tt class="docutils literal"><span class="pre">clear</span></tt>, <tt class="docutils literal"><span class="pre">pop</span></tt>, <tt class="docutils literal"><span class="pre">remove</span></tt>, <tt class="docutils literal"><span class="pre">__ior__</span></tt>,
<tt class="docutils literal"><span class="pre">__iand__</span></tt>, <tt class="docutils literal"><span class="pre">__ixor__</span></tt>, and <tt class="docutils literal"><span class="pre">__isub__</span></tt></td>
</tr>
<tr><td><tt class="xref docutils literal"><span class="pre">Mapping</span></tt></td>
<td><tt class="xref docutils literal"><span class="pre">Sized</span></tt>,
<tt class="xref docutils literal"><span class="pre">Iterable</span></tt>,
<tt class="xref docutils literal"><span class="pre">Container</span></tt></td>
<td><tt class="docutils literal"><span class="pre">__getitem__</span></tt></td>
<td><tt class="docutils literal"><span class="pre">__contains__</span></tt>, <tt class="docutils literal"><span class="pre">keys</span></tt>, <tt class="docutils literal"><span class="pre">items</span></tt>, <tt class="docutils literal"><span class="pre">values</span></tt>,
<tt class="docutils literal"><span class="pre">get</span></tt>, <tt class="docutils literal"><span class="pre">__eq__</span></tt>, and <tt class="docutils literal"><span class="pre">__ne__</span></tt></td>
</tr>
<tr><td><tt class="xref docutils literal"><span class="pre">MutableMapping</span></tt></td>
<td><tt class="xref docutils literal"><span class="pre">Mapping</span></tt></td>
<td><tt class="docutils literal"><span class="pre">__setitem__</span></tt> and
<tt class="docutils literal"><span class="pre">__delitem__</span></tt></td>
<td>Inherited Mapping methods and
<tt class="docutils literal"><span class="pre">pop</span></tt>, <tt class="docutils literal"><span class="pre">popitem</span></tt>, <tt class="docutils literal"><span class="pre">clear</span></tt>, <tt class="docutils literal"><span class="pre">update</span></tt>,
and <tt class="docutils literal"><span class="pre">setdefault</span></tt></td>
</tr>
<tr><td><tt class="xref docutils literal"><span class="pre">MappingView</span></tt></td>
<td><tt class="xref docutils literal"><span class="pre">Sized</span></tt></td>
<td>&nbsp;</td>
<td><tt class="docutils literal"><span class="pre">__len__</span></tt></td>
</tr>
<tr><td><tt class="xref docutils literal"><span class="pre">KeysView</span></tt></td>
<td><tt class="xref docutils literal"><span class="pre">MappingView</span></tt>,
<tt class="xref docutils literal"><span class="pre">Set</span></tt></td>
<td>&nbsp;</td>
<td><tt class="docutils literal"><span class="pre">__contains__</span></tt>,
<tt class="docutils literal"><span class="pre">__iter__</span></tt></td>
</tr>
<tr><td><tt class="xref docutils literal"><span class="pre">ItemsView</span></tt></td>
<td><tt class="xref docutils literal"><span class="pre">MappingView</span></tt>,
<tt class="xref docutils literal"><span class="pre">Set</span></tt></td>
<td>&nbsp;</td>
<td><tt class="docutils literal"><span class="pre">__contains__</span></tt>,
<tt class="docutils literal"><span class="pre">__iter__</span></tt></td>
</tr>
<tr><td><tt class="xref docutils literal"><span class="pre">ValuesView</span></tt></td>
<td><tt class="xref docutils literal"><span class="pre">MappingView</span></tt></td>
<td>&nbsp;</td>
<td><tt class="docutils literal"><span class="pre">__contains__</span></tt>, <tt class="docutils literal"><span class="pre">__iter__</span></tt></td>
</tr>
</tbody>
</table>
<p>These ABCs allow us to ask classes or instances if they provide
particular functionality, for example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">size</span> <span class="o">=</span> <span class="bp">None</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">myvar</span><span class="p">,</span> <span class="n">collections</span><span class="o">.</span><span class="n">Sized</span><span class="p">):</span>
    <span class="n">size</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">myvar</span><span class="p">)</span>
</pre></div>
</div>
<p>Several of the ABCs are also useful as mixins that make it easier to develop
classes supporting container APIs.  For example, to write a class supporting
the full <tt class="xref docutils literal"><span class="pre">Set</span></tt> API, it only necessary to supply the three underlying
abstract methods: <a title="object.__contains__" class="reference external" href="../reference/datamodel.html#object.__contains__"><tt class="xref docutils literal"><span class="pre">__contains__()</span></tt></a>, <a title="object.__iter__" class="reference external" href="../reference/datamodel.html#object.__iter__"><tt class="xref docutils literal"><span class="pre">__iter__()</span></tt></a>, and <a title="object.__len__" class="reference external" href="../reference/datamodel.html#object.__len__"><tt class="xref docutils literal"><span class="pre">__len__()</span></tt></a>.
The ABC supplies the remaining methods such as <a title="object.__and__" class="reference external" href="../reference/datamodel.html#object.__and__"><tt class="xref docutils literal"><span class="pre">__and__()</span></tt></a> and
<tt class="xref docutils literal"><span class="pre">isdisjoint()</span></tt></p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">ListBasedSet</span><span class="p">(</span><span class="n">collections</span><span class="o">.</span><span class="n">Set</span><span class="p">):</span>
     <span class="sd">&#39;&#39;&#39; Alternate set implementation favoring space over speed</span>
<span class="sd">         and not requiring the set elements to be hashable. &#39;&#39;&#39;</span>
     <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">iterable</span><span class="p">):</span>
         <span class="bp">self</span><span class="o">.</span><span class="n">elements</span> <span class="o">=</span> <span class="n">lst</span> <span class="o">=</span> <span class="p">[]</span>
         <span class="k">for</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
             <span class="k">if</span> <span class="n">value</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">lst</span><span class="p">:</span>
                 <span class="n">lst</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
     <span class="k">def</span> <span class="nf">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
         <span class="k">return</span> <span class="nb">iter</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">elements</span><span class="p">)</span>
     <span class="k">def</span> <span class="nf">__contains__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
         <span class="k">return</span> <span class="n">value</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">elements</span>
     <span class="k">def</span> <span class="nf">__len__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
         <span class="k">return</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">elements</span><span class="p">)</span>

<span class="n">s1</span> <span class="o">=</span> <span class="n">ListBasedSet</span><span class="p">(</span><span class="s">&#39;abcdef&#39;</span><span class="p">)</span>
<span class="n">s2</span> <span class="o">=</span> <span class="n">ListBasedSet</span><span class="p">(</span><span class="s">&#39;defghi&#39;</span><span class="p">)</span>
<span class="n">overlap</span> <span class="o">=</span> <span class="n">s1</span> <span class="o">&amp;</span> <span class="n">s2</span>            <span class="c"># The __and__() method is supported automatically</span>
</pre></div>
</div>
<p>Notes on using <tt class="xref docutils literal"><span class="pre">Set</span></tt> and <tt class="xref docutils literal"><span class="pre">MutableSet</span></tt> as a mixin:</p>
<ol class="arabic simple">
<li>Since some set operations create new sets, the default mixin methods need
a way to create new instances from an iterable. The class constructor is
assumed to have a signature in the form <tt class="docutils literal"><span class="pre">ClassName(iterable)</span></tt>.
That assumption is factored-out to an internal classmethod called
<tt class="xref docutils literal"><span class="pre">_from_iterable()</span></tt> which calls <tt class="docutils literal"><span class="pre">cls(iterable)</span></tt> to produce a new set.
If the <tt class="xref docutils literal"><span class="pre">Set</span></tt> mixin is being used in a class with a different
constructor signature, you will need to override <tt class="xref docutils literal"><span class="pre">from_iterable()</span></tt>
with a classmethod that can construct new instances from
an iterable argument.</li>
<li>To override the comparisons (presumably for speed, as the
semantics are fixed), redefine <a title="object.__le__" class="reference external" href="../reference/datamodel.html#object.__le__"><tt class="xref docutils literal"><span class="pre">__le__()</span></tt></a> and
then the other operations will automatically follow suit.</li>
<li>The <tt class="xref docutils literal"><span class="pre">Set</span></tt> mixin provides a <tt class="xref docutils literal"><span class="pre">_hash()</span></tt> method to compute a hash value
for the set; however, <a title="object.__hash__" class="reference external" href="../reference/datamodel.html#object.__hash__"><tt class="xref docutils literal"><span class="pre">__hash__()</span></tt></a> is not defined because not all sets
are hashable or immutable.  To add set hashabilty using mixins,
inherit from both <tt class="xref docutils literal"><span class="pre">Set()</span></tt> and <tt class="xref docutils literal"><span class="pre">Hashable()</span></tt>, then define
<tt class="docutils literal"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">Set._hash</span></tt>.</li>
</ol>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<ul class="last simple">
<li><a class="reference external" href="http://code.activestate.com/recipes/576694/">OrderedSet recipe</a> for an
example built on <tt class="xref docutils literal"><span class="pre">MutableSet</span></tt>.</li>
<li>For more about ABCs, see the <a title="Abstract base classes according to PEP 3119." class="reference external" href="abc.html#module-abc"><tt class="xref docutils literal"><span class="pre">abc</span></tt></a> module and <span class="target" id="index-226"></span><a class="reference external" href="http://www.python.org/dev/peps/pep-3119"><strong>PEP 3119</strong></a>.</li>
</ul>
</div>
</div>
<div class="section" id="deque-objects">
<span id="id1"></span><h2>9.3.2. <a title="collections.deque" class="reference internal" href="#collections.deque"><tt class="xref docutils literal"><span class="pre">deque</span></tt></a> objects<a class="headerlink" href="#deque-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="collections.deque">
<em class="property">
class </em><tt class="descclassname">collections.</tt><tt class="descname">deque</tt><big>(</big><span class="optional">[</span><em>iterable</em><span class="optional">[</span>, <em>maxlen</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#collections.deque" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new deque object initialized left-to-right (using <a title="collections.deque.append" class="reference internal" href="#collections.deque.append"><tt class="xref docutils literal"><span class="pre">append()</span></tt></a>) with
data from <em>iterable</em>.  If <em>iterable</em> is not specified, the new deque is empty.</p>
<p>Deques are a generalization of stacks and queues (the name is pronounced &#8220;deck&#8221;
and is short for &#8220;double-ended queue&#8221;).  Deques support thread-safe, memory
efficient appends and pops from either side of the deque with approximately the
same O(1) performance in either direction.</p>
<p>Though <a title="list" class="reference external" href="functions.html#list"><tt class="xref docutils literal"><span class="pre">list</span></tt></a> objects support similar operations, they are optimized for
fast fixed-length operations and incur O(n) memory movement costs for
<tt class="docutils literal"><span class="pre">pop(0)</span></tt> and <tt class="docutils literal"><span class="pre">insert(0,</span> <span class="pre">v)</span></tt> operations which change both the size and
position of the underlying data representation.</p>
<p>
<span class="versionmodified">New in version 2.4.</span></p>
<p>If <em>maxlen</em> is not specified or is <em>None</em>, deques may grow to an
arbitrary length.  Otherwise, the deque is bounded to the specified maximum
length.  Once a bounded length deque is full, when new items are added, a
corresponding number of items are discarded from the opposite end.  Bounded
length deques provide functionality similar to the <tt class="docutils literal"><span class="pre">tail</span></tt> filter in
Unix. They are also useful for tracking transactions and other pools of data
where only the most recent activity is of interest.</p>
<p>
<span class="versionmodified">Changed in version 2.6: </span>Added <em>maxlen</em> parameter.</p>
<p>Deque objects support the following methods:</p>
<dl class="method">
<dt id="collections.deque.append">
<tt class="descname">append</tt><big>(</big><em>x</em><big>)</big><a class="headerlink" href="#collections.deque.append" title="Permalink to this definition">¶</a></dt>
<dd>Add <em>x</em> to the right side of the deque.</dd></dl>

<dl class="method">
<dt id="collections.deque.appendleft">
<tt class="descname">appendleft</tt><big>(</big><em>x</em><big>)</big><a class="headerlink" href="#collections.deque.appendleft" title="Permalink to this definition">¶</a></dt>
<dd>Add <em>x</em> to the left side of the deque.</dd></dl>

<dl class="method">
<dt id="collections.deque.clear">
<tt class="descname">clear</tt><big>(</big><big>)</big><a class="headerlink" href="#collections.deque.clear" title="Permalink to this definition">¶</a></dt>
<dd>Remove all elements from the deque leaving it with length 0.</dd></dl>

<dl class="method">
<dt id="collections.deque.extend">
<tt class="descname">extend</tt><big>(</big><em>iterable</em><big>)</big><a class="headerlink" href="#collections.deque.extend" title="Permalink to this definition">¶</a></dt>
<dd>Extend the right side of the deque by appending elements from the iterable
argument.</dd></dl>

<dl class="method">
<dt id="collections.deque.extendleft">
<tt class="descname">extendleft</tt><big>(</big><em>iterable</em><big>)</big><a class="headerlink" href="#collections.deque.extendleft" title="Permalink to this definition">¶</a></dt>
<dd>Extend the left side of the deque by appending elements from <em>iterable</em>.
Note, the series of left appends results in reversing the order of
elements in the iterable argument.</dd></dl>

<dl class="method">
<dt id="collections.deque.pop">
<tt class="descname">pop</tt><big>(</big><big>)</big><a class="headerlink" href="#collections.deque.pop" title="Permalink to this definition">¶</a></dt>
<dd>Remove and return an element from the right side of the deque. If no
elements are present, raises an <a title="exceptions.IndexError" class="reference external" href="exceptions.html#exceptions.IndexError"><tt class="xref docutils literal"><span class="pre">IndexError</span></tt></a>.</dd></dl>

<dl class="method">
<dt id="collections.deque.popleft">
<tt class="descname">popleft</tt><big>(</big><big>)</big><a class="headerlink" href="#collections.deque.popleft" title="Permalink to this definition">¶</a></dt>
<dd>Remove and return an element from the left side of the deque. If no
elements are present, raises an <a title="exceptions.IndexError" class="reference external" href="exceptions.html#exceptions.IndexError"><tt class="xref docutils literal"><span class="pre">IndexError</span></tt></a>.</dd></dl>

<dl class="method">
<dt id="collections.deque.remove">
<tt class="descname">remove</tt><big>(</big><em>value</em><big>)</big><a class="headerlink" href="#collections.deque.remove" title="Permalink to this definition">¶</a></dt>
<dd><p>Removed the first occurrence of <em>value</em>.  If not found, raises a
<a title="exceptions.ValueError" class="reference external" href="exceptions.html#exceptions.ValueError"><tt class="xref docutils literal"><span class="pre">ValueError</span></tt></a>.</p>
<p>
<span class="versionmodified">New in version 2.5.</span></p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.rotate">
<tt class="descname">rotate</tt><big>(</big><em>n</em><big>)</big><a class="headerlink" href="#collections.deque.rotate" title="Permalink to this definition">¶</a></dt>
<dd>Rotate the deque <em>n</em> steps to the right.  If <em>n</em> is negative, rotate to
the left.  Rotating one step to the right is equivalent to:
<tt class="docutils literal"><span class="pre">d.appendleft(d.pop())</span></tt>.</dd></dl>

</dd></dl>

<p>In addition to the above, deques support iteration, pickling, <tt class="docutils literal"><span class="pre">len(d)</span></tt>,
<tt class="docutils literal"><span class="pre">reversed(d)</span></tt>, <tt class="docutils literal"><span class="pre">copy.copy(d)</span></tt>, <tt class="docutils literal"><span class="pre">copy.deepcopy(d)</span></tt>, membership testing with
the <a class="reference external" href="../reference/expressions.html#in"><tt class="xref docutils literal"><span class="pre">in</span></tt></a> operator, and subscript references such as <tt class="docutils literal"><span class="pre">d[-1]</span></tt>.  Indexed
access is O(1) at both ends but slows to O(n) in the middle.  For fast random
access, use lists instead.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">deque</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">deque</span><span class="p">(</span><span class="s">&#39;ghi&#39;</span><span class="p">)</span>                 <span class="c"># make a new deque with three items</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">d</span><span class="p">:</span>                   <span class="c"># iterate over the deque&#39;s elements</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="n">elem</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span>
<span class="go">G</span>
<span class="go">H</span>
<span class="go">I</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s">&#39;j&#39;</span><span class="p">)</span>                    <span class="c"># add a new entry to the right side</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">appendleft</span><span class="p">(</span><span class="s">&#39;f&#39;</span><span class="p">)</span>                <span class="c"># add a new entry to the left side</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>                                <span class="c"># show the representation of the deque</span>
<span class="go">deque([&#39;f&#39;, &#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>                          <span class="c"># return and remove the rightmost item</span>
<span class="go">&#39;j&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>                      <span class="c"># return and remove the leftmost item</span>
<span class="go">&#39;f&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>                          <span class="c"># list the contents of the deque</span>
<span class="go">[&#39;g&#39;, &#39;h&#39;, &#39;i&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="mf">0</span><span class="p">]</span>                             <span class="c"># peek at leftmost item</span>
<span class="go">&#39;g&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="o">-</span><span class="mf">1</span><span class="p">]</span>                            <span class="c"># peek at rightmost item</span>
<span class="go">&#39;i&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">reversed</span><span class="p">(</span><span class="n">d</span><span class="p">))</span>                <span class="c"># list the contents of a deque in reverse</span>
<span class="go">[&#39;i&#39;, &#39;h&#39;, &#39;g&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s">&#39;h&#39;</span> <span class="ow">in</span> <span class="n">d</span>                         <span class="c"># search the deque</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="s">&#39;jkl&#39;</span><span class="p">)</span>                  <span class="c"># add multiple elements at once</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">deque([&#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;, &#39;k&#39;, &#39;l&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="mf">1</span><span class="p">)</span>                      <span class="c"># right rotation</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">deque([&#39;l&#39;, &#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;, &#39;k&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="o">-</span><span class="mf">1</span><span class="p">)</span>                     <span class="c"># left rotation</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">deque([&#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;, &#39;k&#39;, &#39;l&#39;])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">deque</span><span class="p">(</span><span class="n">reversed</span><span class="p">(</span><span class="n">d</span><span class="p">))</span>               <span class="c"># make a new deque in reverse order</span>
<span class="go">deque([&#39;l&#39;, &#39;k&#39;, &#39;j&#39;, &#39;i&#39;, &#39;h&#39;, &#39;g&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>                        <span class="c"># empty the deque</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>                          <span class="c"># cannot pop from an empty deque</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;pyshell#6&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">-toplevel-</span>
    <span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="nc">IndexError</span>: <span class="n-Identifier">pop from an empty deque</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">extendleft</span><span class="p">(</span><span class="s">&#39;abc&#39;</span><span class="p">)</span>              <span class="c"># extendleft() reverses the input order</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">deque([&#39;c&#39;, &#39;b&#39;, &#39;a&#39;])</span>
</pre></div>
</div>
<div class="section" id="deque-recipes">
<span id="id2"></span><h3>9.3.2.1. <a title="collections.deque" class="reference internal" href="#collections.deque"><tt class="xref docutils literal"><span class="pre">deque</span></tt></a> Recipes<a class="headerlink" href="#deque-recipes" title="Permalink to this headline">¶</a></h3>
<p>This section shows various approaches to working with deques.</p>
<p>The <tt class="xref docutils literal"><span class="pre">rotate()</span></tt> method provides a way to implement <a title="collections.deque" class="reference internal" href="#collections.deque"><tt class="xref docutils literal"><span class="pre">deque</span></tt></a> slicing and
deletion.  For example, a pure python implementation of <tt class="docutils literal"><span class="pre">del</span> <span class="pre">d[n]</span></tt> relies on
the <tt class="xref docutils literal"><span class="pre">rotate()</span></tt> method to position elements to be popped:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">delete_nth</span><span class="p">(</span><span class="n">d</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
    <span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="o">-</span><span class="n">n</span><span class="p">)</span>
    <span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>
    <span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
</pre></div>
</div>
<p>To implement <a title="collections.deque" class="reference internal" href="#collections.deque"><tt class="xref docutils literal"><span class="pre">deque</span></tt></a> slicing, use a similar approach applying
<tt class="xref docutils literal"><span class="pre">rotate()</span></tt> to bring a target element to the left side of the deque. Remove
old entries with <tt class="xref docutils literal"><span class="pre">popleft()</span></tt>, add new entries with <tt class="xref docutils literal"><span class="pre">extend()</span></tt>, and then
reverse the rotation.
With minor variations on that approach, it is easy to implement Forth style
stack manipulations such as <tt class="docutils literal"><span class="pre">dup</span></tt>, <tt class="docutils literal"><span class="pre">drop</span></tt>, <tt class="docutils literal"><span class="pre">swap</span></tt>, <tt class="docutils literal"><span class="pre">over</span></tt>, <tt class="docutils literal"><span class="pre">pick</span></tt>,
<tt class="docutils literal"><span class="pre">rot</span></tt>, and <tt class="docutils literal"><span class="pre">roll</span></tt>.</p>
<p>Multi-pass data reduction algorithms can be succinctly expressed and efficiently
coded by extracting elements with multiple calls to <tt class="xref docutils literal"><span class="pre">popleft()</span></tt>, applying
a reduction function, and calling <tt class="xref docutils literal"><span class="pre">append()</span></tt> to add the result back to the
deque.</p>
<p>For example, building a balanced binary tree of nested lists entails reducing
two adjacent nodes into one by grouping them in a list:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">maketree</span><span class="p">(</span><span class="n">iterable</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">d</span> <span class="o">=</span> <span class="n">deque</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">while</span> <span class="nb">len</span><span class="p">(</span><span class="n">d</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mf">1</span><span class="p">:</span>
<span class="gp">... </span>        <span class="n">pair</span> <span class="o">=</span> <span class="p">[</span><span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">(),</span> <span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()]</span>
<span class="gp">... </span>        <span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">pair</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="nb">list</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">maketree</span><span class="p">(</span><span class="s">&#39;abcdefgh&#39;</span><span class="p">)</span>
<span class="go">[[[[&#39;a&#39;, &#39;b&#39;], [&#39;c&#39;, &#39;d&#39;]], [[&#39;e&#39;, &#39;f&#39;], [&#39;g&#39;, &#39;h&#39;]]]]</span>
</pre></div>
</div>
<p>Bounded length deques provide functionality similar to the <tt class="docutils literal"><span class="pre">tail</span></tt> filter
in Unix:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">tail</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">n</span><span class="o">=</span><span class="mf">10</span><span class="p">):</span>
    <span class="s">&#39;Return the last n lines of a file&#39;</span>
    <span class="k">return</span> <span class="n">deque</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">),</span> <span class="n">n</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="defaultdict-objects">
<span id="id3"></span><h2>9.3.3. <a title="collections.defaultdict" class="reference internal" href="#collections.defaultdict"><tt class="xref docutils literal"><span class="pre">defaultdict</span></tt></a> objects<a class="headerlink" href="#defaultdict-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="collections.defaultdict">
<em class="property">
class </em><tt class="descclassname">collections.</tt><tt class="descname">defaultdict</tt><big>(</big><span class="optional">[</span><em>default_factory</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="optional">]</span><big>)</big><a class="headerlink" href="#collections.defaultdict" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new dictionary-like object.  <a title="collections.defaultdict" class="reference internal" href="#collections.defaultdict"><tt class="xref docutils literal"><span class="pre">defaultdict</span></tt></a> is a subclass of the
builtin <a title="dict" class="reference external" href="stdtypes.html#dict"><tt class="xref docutils literal"><span class="pre">dict</span></tt></a> class.  It overrides one method and adds one writable
instance variable.  The remaining functionality is the same as for the
<a title="dict" class="reference external" href="stdtypes.html#dict"><tt class="xref docutils literal"><span class="pre">dict</span></tt></a> class and is not documented here.</p>
<p>The first argument provides the initial value for the <a title="collections.defaultdict.default_factory" class="reference internal" href="#collections.defaultdict.default_factory"><tt class="xref docutils literal"><span class="pre">default_factory</span></tt></a>
attribute; it defaults to <tt class="xref docutils literal"><span class="pre">None</span></tt>. All remaining arguments are treated the same
as if they were passed to the <a title="dict" class="reference external" href="stdtypes.html#dict"><tt class="xref docutils literal"><span class="pre">dict</span></tt></a> constructor, including keyword
arguments.</p>
<p>
<span class="versionmodified">New in version 2.5.</span></p>
<p><a title="collections.defaultdict" class="reference internal" href="#collections.defaultdict"><tt class="xref docutils literal"><span class="pre">defaultdict</span></tt></a> objects support the following method in addition to the
standard <a title="dict" class="reference external" href="stdtypes.html#dict"><tt class="xref docutils literal"><span class="pre">dict</span></tt></a> operations:</p>
<dl class="method">
<dt id="collections.defaultdict.__missing__">
<tt class="descname">__missing__</tt><big>(</big><em>key</em><big>)</big><a class="headerlink" href="#collections.defaultdict.__missing__" title="Permalink to this definition">¶</a></dt>
<dd><p>If the <a title="collections.defaultdict.default_factory" class="reference internal" href="#collections.defaultdict.default_factory"><tt class="xref docutils literal"><span class="pre">default_factory</span></tt></a> attribute is <tt class="xref docutils literal"><span class="pre">None</span></tt>, this raises a
<a title="exceptions.KeyError" class="reference external" href="exceptions.html#exceptions.KeyError"><tt class="xref docutils literal"><span class="pre">KeyError</span></tt></a> exception with the <em>key</em> as argument.</p>
<p>If <a title="collections.defaultdict.default_factory" class="reference internal" href="#collections.defaultdict.default_factory"><tt class="xref docutils literal"><span class="pre">default_factory</span></tt></a> is not <tt class="xref docutils literal"><span class="pre">None</span></tt>, it is called without arguments
to provide a default value for the given <em>key</em>, this value is inserted in
the dictionary for the <em>key</em>, and returned.</p>
<p>If calling <a title="collections.defaultdict.default_factory" class="reference internal" href="#collections.defaultdict.default_factory"><tt class="xref docutils literal"><span class="pre">default_factory</span></tt></a> raises an exception this exception is
propagated unchanged.</p>
<p>This method is called by the <a title="object.__getitem__" class="reference external" href="../reference/datamodel.html#object.__getitem__"><tt class="xref docutils literal"><span class="pre">__getitem__()</span></tt></a> method of the
<a title="dict" class="reference external" href="stdtypes.html#dict"><tt class="xref docutils literal"><span class="pre">dict</span></tt></a> class when the requested key is not found; whatever it
returns or raises is then returned or raised by <a title="object.__getitem__" class="reference external" href="../reference/datamodel.html#object.__getitem__"><tt class="xref docutils literal"><span class="pre">__getitem__()</span></tt></a>.</p>
</dd></dl>

<p><a title="collections.defaultdict" class="reference internal" href="#collections.defaultdict"><tt class="xref docutils literal"><span class="pre">defaultdict</span></tt></a> objects support the following instance variable:</p>
<dl class="attribute">
<dt id="collections.defaultdict.default_factory">
<tt class="descname">default_factory</tt><a class="headerlink" href="#collections.defaultdict.default_factory" title="Permalink to this definition">¶</a></dt>
<dd>This attribute is used by the <a title="collections.defaultdict.__missing__" class="reference internal" href="#collections.defaultdict.__missing__"><tt class="xref docutils literal"><span class="pre">__missing__()</span></tt></a> method; it is
initialized from the first argument to the constructor, if present, or to
<tt class="xref docutils literal"><span class="pre">None</span></tt>, if absent.</dd></dl>

</dd></dl>

<div class="section" id="defaultdict-examples">
<span id="id4"></span><h3>9.3.3.1. <a title="collections.defaultdict" class="reference internal" href="#collections.defaultdict"><tt class="xref docutils literal"><span class="pre">defaultdict</span></tt></a> Examples<a class="headerlink" href="#defaultdict-examples" title="Permalink to this headline">¶</a></h3>
<p>Using <a title="list" class="reference external" href="functions.html#list"><tt class="xref docutils literal"><span class="pre">list</span></tt></a> as the <tt class="xref docutils literal"><span class="pre">default_factory</span></tt>, it is easy to group a
sequence of key-value pairs into a dictionary of lists:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="p">[(</span><span class="s">&#39;yellow&#39;</span><span class="p">,</span> <span class="mf">1</span><span class="p">),</span> <span class="p">(</span><span class="s">&#39;blue&#39;</span><span class="p">,</span> <span class="mf">2</span><span class="p">),</span> <span class="p">(</span><span class="s">&#39;yellow&#39;</span><span class="p">,</span> <span class="mf">3</span><span class="p">),</span> <span class="p">(</span><span class="s">&#39;blue&#39;</span><span class="p">,</span> <span class="mf">4</span><span class="p">),</span> <span class="p">(</span><span class="s">&#39;red&#39;</span><span class="p">,</span> <span class="mf">1</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="nb">list</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="p">[</span><span class="n">k</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="go">[(&#39;blue&#39;, [2, 4]), (&#39;red&#39;, [1]), (&#39;yellow&#39;, [1, 3])]</span>
</pre></div>
</div>
<p>When each key is encountered for the first time, it is not already in the
mapping; so an entry is automatically created using the <tt class="xref docutils literal"><span class="pre">default_factory</span></tt>
function which returns an empty <a title="list" class="reference external" href="functions.html#list"><tt class="xref docutils literal"><span class="pre">list</span></tt></a>.  The <tt class="xref docutils literal"><span class="pre">list.append()</span></tt>
operation then attaches the value to the new list.  When keys are encountered
again, the look-up proceeds normally (returning the list for that key) and the
<tt class="xref docutils literal"><span class="pre">list.append()</span></tt> operation adds another value to the list. This technique is
simpler and faster than an equivalent technique using <a title="dict.setdefault" class="reference external" href="stdtypes.html#dict.setdefault"><tt class="xref docutils literal"><span class="pre">dict.setdefault()</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="o">.</span><span class="n">setdefault</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="p">[])</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="go">[(&#39;blue&#39;, [2, 4]), (&#39;red&#39;, [1]), (&#39;yellow&#39;, [1, 3])]</span>
</pre></div>
</div>
<p>Setting the <tt class="xref docutils literal"><span class="pre">default_factory</span></tt> to <a title="int" class="reference external" href="functions.html#int"><tt class="xref docutils literal"><span class="pre">int</span></tt></a> makes the
<a title="collections.defaultdict" class="reference internal" href="#collections.defaultdict"><tt class="xref docutils literal"><span class="pre">defaultdict</span></tt></a> useful for counting (like a bag or multiset in other
languages):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s">&#39;mississippi&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="p">[</span><span class="n">k</span><span class="p">]</span> <span class="o">+=</span> <span class="mf">1</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="go">[(&#39;i&#39;, 4), (&#39;p&#39;, 2), (&#39;s&#39;, 4), (&#39;m&#39;, 1)]</span>
</pre></div>
</div>
<p>When a letter is first encountered, it is missing from the mapping, so the
<tt class="xref docutils literal"><span class="pre">default_factory</span></tt> function calls <a title="int" class="reference external" href="functions.html#int"><tt class="xref docutils literal"><span class="pre">int()</span></tt></a> to supply a default count of
zero.  The increment operation then builds up the count for each letter.</p>
<p>The function <a title="int" class="reference external" href="functions.html#int"><tt class="xref docutils literal"><span class="pre">int()</span></tt></a> which always returns zero is just a special case of
constant functions.  A faster and more flexible way to create constant functions
is to use <a title="itertools.repeat" class="reference external" href="itertools.html#itertools.repeat"><tt class="xref docutils literal"><span class="pre">itertools.repeat()</span></tt></a> which can supply any constant value (not just
zero):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">constant_factory</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">itertools</span><span class="o">.</span><span class="n">repeat</span><span class="p">(</span><span class="n">value</span><span class="p">)</span><span class="o">.</span><span class="n">next</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="n">constant_factory</span><span class="p">(</span><span class="s">&#39;&lt;missing&gt;&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&#39;John&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&#39;ran&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s">&#39;</span><span class="si">%(name)s</span><span class="s"> </span><span class="si">%(action)s</span><span class="s"> to </span><span class="si">%(object)s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">d</span>
<span class="go">&#39;John ran to &lt;missing&gt;&#39;</span>
</pre></div>
</div>
<p>Setting the <tt class="xref docutils literal"><span class="pre">default_factory</span></tt> to <a title="set" class="reference external" href="stdtypes.html#set"><tt class="xref docutils literal"><span class="pre">set</span></tt></a> makes the
<a title="collections.defaultdict" class="reference internal" href="#collections.defaultdict"><tt class="xref docutils literal"><span class="pre">defaultdict</span></tt></a> useful for building a dictionary of sets:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="p">[(</span><span class="s">&#39;red&#39;</span><span class="p">,</span> <span class="mf">1</span><span class="p">),</span> <span class="p">(</span><span class="s">&#39;blue&#39;</span><span class="p">,</span> <span class="mf">2</span><span class="p">),</span> <span class="p">(</span><span class="s">&#39;red&#39;</span><span class="p">,</span> <span class="mf">3</span><span class="p">),</span> <span class="p">(</span><span class="s">&#39;blue&#39;</span><span class="p">,</span> <span class="mf">4</span><span class="p">),</span> <span class="p">(</span><span class="s">&#39;red&#39;</span><span class="p">,</span> <span class="mf">1</span><span class="p">),</span> <span class="p">(</span><span class="s">&#39;blue&#39;</span><span class="p">,</span> <span class="mf">4</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="n">set</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="p">[</span><span class="n">k</span><span class="p">]</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="go">[(&#39;blue&#39;, set([2, 4])), (&#39;red&#39;, set([1, 3]))]</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="namedtuple-factory-function-for-tuples-with-named-fields">
<span id="named-tuple-factory"></span><h2>9.3.4. <a title="collections.namedtuple" class="reference internal" href="#collections.namedtuple"><tt class="xref docutils literal"><span class="pre">namedtuple()</span></tt></a> Factory Function for Tuples with Named Fields<a class="headerlink" href="#namedtuple-factory-function-for-tuples-with-named-fields" title="Permalink to this headline">¶</a></h2>
<p>Named tuples assign meaning to each position in a tuple and allow for more readable,
self-documenting code.  They can be used wherever regular tuples are used, and
they add the ability to access fields by name instead of position index.</p>
<dl class="function">
<dt id="collections.namedtuple">
<tt class="descclassname">collections.</tt><tt class="descname">namedtuple</tt><big>(</big><em>typename</em>, <em>field_names</em><span class="optional">[</span>, <em>verbose</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#collections.namedtuple" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new tuple subclass named <em>typename</em>.  The new subclass is used to
create tuple-like objects that have fields accessible by attribute lookup as
well as being indexable and iterable.  Instances of the subclass also have a
helpful docstring (with typename and field_names) and a helpful <a title="object.__repr__" class="reference external" href="../reference/datamodel.html#object.__repr__"><tt class="xref docutils literal"><span class="pre">__repr__()</span></tt></a>
method which lists the tuple contents in a <tt class="docutils literal"><span class="pre">name=value</span></tt> format.</p>
<p>The <em>field_names</em> are a single string with each fieldname separated by whitespace
and/or commas, for example <tt class="docutils literal"><span class="pre">'x</span> <span class="pre">y'</span></tt> or <tt class="docutils literal"><span class="pre">'x,</span> <span class="pre">y'</span></tt>.  Alternatively, <em>field_names</em>
can be a sequence of strings such as <tt class="docutils literal"><span class="pre">['x',</span> <span class="pre">'y']</span></tt>.</p>
<p>Any valid Python identifier may be used for a fieldname except for names
starting with an underscore.  Valid identifiers consist of letters, digits,
and underscores but do not start with a digit or underscore and cannot be
a <a title="Test whether a string is a keyword in Python." class="reference external" href="keyword.html#module-keyword"><tt class="xref docutils literal"><span class="pre">keyword</span></tt></a> such as <em>class</em>, <em>for</em>, <em>return</em>, <em>global</em>, <em>pass</em>, <em>print</em>,
or <em>raise</em>.</p>
<p>If <em>verbose</em> is true, the class definition is printed just before being built.</p>
<p>Named tuple instances do not have per-instance dictionaries, so they are
lightweight and require no more memory than regular tuples.</p>
<p>
<span class="versionmodified">New in version 2.6.</span></p>
</dd></dl>

<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Point</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s">&#39;Point&#39;</span><span class="p">,</span> <span class="s">&#39;x y&#39;</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="go">class Point(tuple):</span>
<span class="go">        &#39;Point(x, y)&#39;</span>

<span class="go">        __slots__ = ()</span>

<span class="go">        _fields = (&#39;x&#39;, &#39;y&#39;)</span>

<span class="go">        def __new__(cls, x, y):</span>
<span class="go">            return tuple.__new__(cls, (x, y))</span>

<span class="go">        @classmethod</span>
<span class="go">        def _make(cls, iterable, new=tuple.__new__, len=len):</span>
<span class="go">            &#39;Make a new Point object from a sequence or iterable&#39;</span>
<span class="go">            result = new(cls, iterable)</span>
<span class="go">            if len(result) != 2:</span>
<span class="go">                raise TypeError(&#39;Expected 2 arguments, got %d&#39; % len(result))</span>
<span class="go">            return result</span>

<span class="go">        def __repr__(self):</span>
<span class="go">            return &#39;Point(x=%r, y=%r)&#39; % self</span>

<span class="go">        def _asdict(t):</span>
<span class="go">            &#39;Return a new dict which maps field names to their values&#39;</span>
<span class="go">            return {&#39;x&#39;: t[0], &#39;y&#39;: t[1]}</span>

<span class="go">        def _replace(self, **kwds):</span>
<span class="go">            &#39;Return a new Point object replacing specified fields with new values&#39;</span>
<span class="go">            result = self._make(map(kwds.pop, (&#39;x&#39;, &#39;y&#39;), self))</span>
<span class="go">            if kwds:</span>
<span class="go">                raise ValueError(&#39;Got unexpected field names: %r&#39; % kwds.keys())</span>
<span class="go">            return result</span>

<span class="go">        def __getnewargs__(self):</span>
<span class="go">            return tuple(self)</span>

<span class="go">        x = property(itemgetter(0))</span>
<span class="go">        y = property(itemgetter(1))</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Point</span><span class="p">(</span><span class="mf">11</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mf">22</span><span class="p">)</span>     <span class="c"># instantiate with positional or keyword arguments</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="p">[</span><span class="mf">0</span><span class="p">]</span> <span class="o">+</span> <span class="n">p</span><span class="p">[</span><span class="mf">1</span><span class="p">]</span>             <span class="c"># indexable like the plain tuple (11, 22)</span>
<span class="go">33</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">p</span>                <span class="c"># unpack like a regular tuple</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="p">,</span> <span class="n">y</span>
<span class="go">(11, 22)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">x</span> <span class="o">+</span> <span class="n">p</span><span class="o">.</span><span class="n">y</span>               <span class="c"># fields also accessible by name</span>
<span class="go">33</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span>                       <span class="c"># readable __repr__ with a name=value style</span>
<span class="go">Point(x=11, y=22)</span>
</pre></div>
</div>
<p>Named tuples are especially useful for assigning field names to result tuples returned
by the <a title="Write and read tabular data to and from delimited files." class="reference external" href="csv.html#module-csv"><tt class="xref docutils literal"><span class="pre">csv</span></tt></a> or <a title="A DB-API 2.0 implementation using SQLite 3.x." class="reference external" href="sqlite3.html#module-sqlite3"><tt class="xref docutils literal"><span class="pre">sqlite3</span></tt></a> modules:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">EmployeeRecord</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s">&#39;EmployeeRecord&#39;</span><span class="p">,</span> <span class="s">&#39;name, age, title, department, paygrade&#39;</span><span class="p">)</span>

<span class="kn">import</span> <span class="nn">csv</span>
<span class="k">for</span> <span class="n">emp</span> <span class="ow">in</span> <span class="nb">map</span><span class="p">(</span><span class="n">EmployeeRecord</span><span class="o">.</span><span class="n">_make</span><span class="p">,</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="s">&quot;employees.csv&quot;</span><span class="p">,</span> <span class="s">&quot;rb&quot;</span><span class="p">))):</span>
    <span class="k">print</span> <span class="n">emp</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">emp</span><span class="o">.</span><span class="n">title</span>

<span class="kn">import</span> <span class="nn">sqlite3</span>
<span class="n">conn</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s">&#39;/companydata&#39;</span><span class="p">)</span>
<span class="n">cursor</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&#39;SELECT name, age, title, department, paygrade FROM employees&#39;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">emp</span> <span class="ow">in</span> <span class="nb">map</span><span class="p">(</span><span class="n">EmployeeRecord</span><span class="o">.</span><span class="n">_make</span><span class="p">,</span> <span class="n">cursor</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()):</span>
    <span class="k">print</span> <span class="n">emp</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">emp</span><span class="o">.</span><span class="n">title</span>
</pre></div>
</div>
<p>In addition to the methods inherited from tuples, named tuples support
three additional methods and one attribute.  To prevent conflicts with
field names, the method and attribute names start with an underscore.</p>
<dl class="method">
<dt id="collections.somenamedtuple._make">
<tt class="descclassname">somenamedtuple.</tt><tt class="descname">_make</tt><big>(</big><em>iterable</em><big>)</big><a class="headerlink" href="#collections.somenamedtuple._make" title="Permalink to this definition">¶</a></dt>
<dd>Class method that makes a new instance from an existing sequence or iterable.</dd></dl>

<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="p">[</span><span class="mf">11</span><span class="p">,</span> <span class="mf">22</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Point</span><span class="o">.</span><span class="n">_make</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
<span class="go">Point(x=11, y=22)</span>
</pre></div>
</div>
<dl class="method">
<dt id="collections.somenamedtuple._asdict">
<tt class="descclassname">somenamedtuple.</tt><tt class="descname">_asdict</tt><big>(</big><big>)</big><a class="headerlink" href="#collections.somenamedtuple._asdict" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new dict which maps field names to their corresponding values:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">_asdict</span><span class="p">()</span>
<span class="go">{&#39;x&#39;: 11, &#39;y&#39;: 22}</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.somenamedtuple._replace">
<tt class="descclassname">somenamedtuple.</tt><tt class="descname">_replace</tt><big>(</big><em>kwargs</em><big>)</big><a class="headerlink" href="#collections.somenamedtuple._replace" title="Permalink to this definition">¶</a></dt>
<dd>Return a new instance of the named tuple replacing specified fields with new
values:</dd></dl>

<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Point</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mf">11</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mf">22</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mf">33</span><span class="p">)</span>
<span class="go">Point(x=33, y=22)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">partnum</span><span class="p">,</span> <span class="n">record</span> <span class="ow">in</span> <span class="n">inventory</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
<span class="gp">... </span>    <span class="n">inventory</span><span class="p">[</span><span class="n">partnum</span><span class="p">]</span> <span class="o">=</span> <span class="n">record</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">price</span><span class="o">=</span><span class="n">newprices</span><span class="p">[</span><span class="n">partnum</span><span class="p">],</span> <span class="n">timestamp</span><span class="o">=</span><span class="n">time</span><span class="o">.</span><span class="n">now</span><span class="p">())</span>
</pre></div>
</div>
<dl class="attribute">
<dt id="collections.somenamedtuple._fields">
<tt class="descclassname">somenamedtuple.</tt><tt class="descname">_fields</tt><a class="headerlink" href="#collections.somenamedtuple._fields" title="Permalink to this definition">¶</a></dt>
<dd>Tuple of strings listing the field names.  Useful for introspection
and for creating new named tuple types from existing named tuples.</dd></dl>

<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">_fields</span>            <span class="c"># view the field names</span>
<span class="go">(&#39;x&#39;, &#39;y&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Color</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s">&#39;Color&#39;</span><span class="p">,</span> <span class="s">&#39;red green blue&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Pixel</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s">&#39;Pixel&#39;</span><span class="p">,</span> <span class="n">Point</span><span class="o">.</span><span class="n">_fields</span> <span class="o">+</span> <span class="n">Color</span><span class="o">.</span><span class="n">_fields</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Pixel</span><span class="p">(</span><span class="mf">11</span><span class="p">,</span> <span class="mf">22</span><span class="p">,</span> <span class="mf">128</span><span class="p">,</span> <span class="mf">255</span><span class="p">,</span> <span class="mf">0</span><span class="p">)</span>
<span class="go">Pixel(x=11, y=22, red=128, green=255, blue=0)</span>
</pre></div>
</div>
<p>To retrieve a field whose name is stored in a string, use the <a title="getattr" class="reference external" href="functions.html#getattr"><tt class="xref docutils literal"><span class="pre">getattr()</span></tt></a>
function:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">getattr</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="s">&#39;x&#39;</span><span class="p">)</span>
<span class="go">11</span>
</pre></div>
</div>
<p>To convert a dictionary to a named tuple, use the double-star-operator
(as described in <a class="reference external" href="../tutorial/controlflow.html#tut-unpacking-arguments"><em>Unpacking Argument Lists</em></a>):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s">&#39;x&#39;</span><span class="p">:</span> <span class="mf">11</span><span class="p">,</span> <span class="s">&#39;y&#39;</span><span class="p">:</span> <span class="mf">22</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Point</span><span class="p">(</span><span class="o">**</span><span class="n">d</span><span class="p">)</span>
<span class="go">Point(x=11, y=22)</span>
</pre></div>
</div>
<p>Since a named tuple is a regular Python class, it is easy to add or change
functionality with a subclass.  Here is how to add a calculated field and
a fixed-width print format:</p>
<blockquote>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Point</span><span class="p">(</span><span class="n">namedtuple</span><span class="p">(</span><span class="s">&#39;Point&#39;</span><span class="p">,</span> <span class="s">&#39;x y&#39;</span><span class="p">)):</span>
<span class="gp">... </span>    <span class="n">__slots__</span> <span class="o">=</span> <span class="p">()</span>
<span class="gp">... </span>    <span class="nd">@property</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">hypot</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">x</span> <span class="o">**</span> <span class="mf">2</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span> <span class="o">**</span> <span class="mf">2</span><span class="p">)</span> <span class="o">**</span> <span class="mf">0.5</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="s">&#39;Point: x=</span><span class="si">%6.3f</span><span class="s">  y=</span><span class="si">%6.3f</span><span class="s">  hypot=</span><span class="si">%6.3f</span><span class="s">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">hypot</span><span class="p">)</span>
</pre></div>
</div>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">Point</span><span class="p">(</span><span class="mf">3</span><span class="p">,</span> <span class="mf">4</span><span class="p">),</span> <span class="n">Point</span><span class="p">(</span><span class="mf">14</span><span class="p">,</span> <span class="mf">5</span><span class="o">/</span><span class="mf">7.</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="n">p</span>
<span class="go">Point: x= 3.000  y= 4.000  hypot= 5.000</span>
<span class="go">Point: x=14.000  y= 0.714  hypot=14.018</span>
</pre></div>
</div>
</blockquote>
<p>The subclass shown above sets <tt class="docutils literal"><span class="pre">__slots__</span></tt> to an empty tuple.  This keeps
keep memory requirements low by preventing the creation of instance dictionaries.</p>
<p>Subclassing is not useful for adding new, stored fields.  Instead, simply
create a new named tuple type from the <tt class="xref docutils literal"><span class="pre">_fields</span></tt> attribute:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Point3D</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s">&#39;Point3D&#39;</span><span class="p">,</span> <span class="n">Point</span><span class="o">.</span><span class="n">_fields</span> <span class="o">+</span> <span class="p">(</span><span class="s">&#39;z&#39;</span><span class="p">,))</span>
</pre></div>
</div>
<p>Default values can be implemented by using <tt class="xref docutils literal"><span class="pre">_replace()</span></tt> to
customize a prototype instance:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Account</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s">&#39;Account&#39;</span><span class="p">,</span> <span class="s">&#39;owner balance transaction_count&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">default_account</span> <span class="o">=</span> <span class="n">Account</span><span class="p">(</span><span class="s">&#39;&lt;owner name&gt;&#39;</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span> <span class="mf">0</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">johns_account</span> <span class="o">=</span> <span class="n">default_account</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">owner</span><span class="o">=</span><span class="s">&#39;John&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Enumerated constants can be implemented with named tuples, but it is simpler
and more efficient to use a simple class declaration:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Status</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s">&#39;Status&#39;</span><span class="p">,</span> <span class="s">&#39;open pending closed&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">_make</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mf">3</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Status</span><span class="o">.</span><span class="n">open</span><span class="p">,</span> <span class="n">Status</span><span class="o">.</span><span class="n">pending</span><span class="p">,</span> <span class="n">Status</span><span class="o">.</span><span class="n">closed</span>
<span class="go">(0, 1, 2)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Status</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">open</span><span class="p">,</span> <span class="n">pending</span><span class="p">,</span> <span class="n">closed</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mf">3</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="http://code.activestate.com/recipes/500261/">Named tuple recipe</a>
adapted for Python 2.4.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h3><a href="../contents.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference external" href="">9.3. <tt class="docutils literal"><span class="pre">collections</span></tt> &#8212; High-performance container datatypes</a><ul>
<li><a class="reference external" href="#abcs-abstract-base-classes">9.3.1. ABCs - abstract base classes</a></li>
<li><a class="reference external" href="#deque-objects">9.3.2. <tt class="docutils literal"><span class="pre">deque</span></tt> objects</a><ul>
<li><a class="reference external" href="#deque-recipes">9.3.2.1. <tt class="docutils literal"><span class="pre">deque</span></tt> Recipes</a></li>
</ul>
</li>
<li><a class="reference external" href="#defaultdict-objects">9.3.3. <tt class="docutils literal"><span class="pre">defaultdict</span></tt> objects</a><ul>
<li><a class="reference external" href="#defaultdict-examples">9.3.3.1. <tt class="docutils literal"><span class="pre">defaultdict</span></tt> Examples</a></li>
</ul>
</li>
<li><a class="reference external" href="#namedtuple-factory-function-for-tuples-with-named-fields">9.3.4. <tt class="docutils literal"><span class="pre">namedtuple()</span></tt> Factory Function for Tuples with Named Fields</a></li>
</ul>
</li>
</ul>

            <h4>Previous topic</h4>
            <p class="topless"><a href="calendar.html"
                                  title="previous chapter">9.2. <tt class="docutils literal docutils literal"><span class="pre">calendar</span></tt> &#8212; General calendar-related functions</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="heapq.html"
                                  title="next chapter">9.4. <tt class="docutils literal docutils literal"><span class="pre">heapq</span></tt> &#8212; Heap queue algorithm</a></p>
            <h3>This Page</h3>
            <ul class="this-page-menu">
              <li><a href="../_sources/library/collections.txt"
                     rel="nofollow">Show Source</a></li>
            </ul>
          <div id="searchbox" style="display: none">
            <h3>Quick search</h3>
              <form class="search" action="../search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>
              <p class="searchtip" style="font-size: 90%">
              Enter search terms or a module, class or function name.
              </p>
          </div>
          <script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../modindex.html" title="Global Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="heapq.html" title="9.4. heapq — Heap queue algorithm"
             >next</a> |</li>
        <li class="right" >
          <a href="calendar.html" title="9.2. calendar — General calendar-related functions"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v2.6.2 documentation</a> &raquo;</li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
          <li><a href="datatypes.html" >9. Data Types</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
      &copy; <a href="../copyright.html">Copyright</a> 1990-2009, Python Software Foundation.
      Last updated on Apr 15, 2009.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.6.1.
    </div>
  </body>
</html>